package com.menqui.localizame.Activity;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.menqui.localizame.R;
import com.menqui.localizame.constantes.ConstantesConfiguracion;
import com.menqui.localizame.estructuras.DatosRuta;
import com.menqui.localizame.webservice.LocalizameWebService;

public class IniciadorRutasActivity extends Activity implements View.OnClickListener {

	private RadioGroup rutasRadioGroup = null;

	private Button btIniciar = null;
	private int rutaSeleccionada = -1;

	@Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.iniciar_ruta);

        btIniciar = (Button) findViewById(R.id.btIniciar);
        btIniciar.setOnClickListener(this);

        rutasRadioGroup = (RadioGroup) findViewById(R.id.rgRutas);

        addOpcionesToRutasRadioGroup();

        rutasRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

			public void onCheckedChanged(RadioGroup group, int checkedId) {
				rutaSeleccionada = checkedId;
			}
		});
    }

	private void addOpcionesToRutasRadioGroup() {

		RadioButton newRadioButton = new RadioButton(this);
        newRadioButton.setText(R.string.msgCrearUnaNuevaRuta);
        newRadioButton.setId(0);
        LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
                RadioGroup.LayoutParams.WRAP_CONTENT,
                RadioGroup.LayoutParams.WRAP_CONTENT);
        rutasRadioGroup.addView(newRadioButton, 0, layoutParams);

		List<DatosRuta> rutas = LocalizameWebService.listarRutas(ConstantesConfiguracion.USERNAME);

		int index = 1;
		for (DatosRuta iter : rutas){
			newRadioButton = new RadioButton(this);
	        newRadioButton.setText(iter.getNombreRuta());
	        newRadioButton.setId(iter.getIdRuta().intValue());
	        layoutParams = new RadioGroup.LayoutParams(
	                RadioGroup.LayoutParams.WRAP_CONTENT,
	                RadioGroup.LayoutParams.WRAP_CONTENT);
	        rutasRadioGroup.addView(newRadioButton, index, layoutParams);
	        index++;
		}
	}

	public void onClick(View v) {
		if (rutaSeleccionada != -1) {

			Intent resultIntent = new Intent();
			resultIntent.putExtra("idruta", String.valueOf(rutaSeleccionada));
			setResult(Activity.RESULT_OK, resultIntent);
			finish();
		} else {
			((TextView) findViewById(R.id.msgElegirRuta)).setText(R.string.msgErrorRutaObligatoria);
		}
	}

}